import axios from 'axios'
let baseURL = 'http://localhost:8801' //测试环境的域名，上线的时候这里缓存线上的接口域名就OK
const instance = axios.create({
    baseURL,
    timeout : 3000
})

// 请求拦截
instance.interceptors.request.use(
    config => {
		   const token =  uni.getStorageSync('token')
		    if (token) {
				// 设置头部token
		      config.headers['token'] = token
		    }
        return config
    },
    error => {
        return Promise.reject( error );
    }
);

// 响应拦截
instance.interceptors.response.use( res => {
    if ( res.status == 200 ){
        return res;
    } else {
        return Promise.reject( res.data.msg );
    }
});

// 自定义适配器 ， 适配uniapp语法
axios.defaults.adapter = function( config ) {
    return new Promise( ( resolve , reject ) => {
        let settle = require('axios/lib/core/settle');
        let buildURL = require('axios/lib/helpers/buildURL');
        uni.request({
            method : config.method.toUpperCase(),
            url : config.baseURL + buildURL( config.url , config.params , config.paramsSerializer ),
            header : config.headers,
            data : config.data,
            dataType : config.dataType,
            responseType : config.responseType,
            sslVerify : config.sslVerify,
            complete : function complete( response ) {
                response = {
                    data : response.data,
                    status : response.statusCode,
                    errMsg : response.errMsg,
                    header : response.header,
                    config : config
                };
            settle( resolve , reject , response );
            },
        });
    })
}


export default instance